package com.pzl.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.orhanobut.logger.Logger;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;


@SuppressLint("NewApi")
public class FileUtil {

    public static String SDCARD_APP_ROOT = "";
    /**
     * apk升级
     */
    public static String SDCARD_APK_DIR = SDCARD_APP_ROOT + File.separator + "APK";
    /**
     * 压缩文件
     */
    public static String SDCARD_ZIP_DIR = SDCARD_APP_ROOT + File.separator + "zip";
    /**
     * 下载文件
     */
    public static String SDCARD_LOAD_FILE_DIR = SDCARD_APP_ROOT + File.separator + "DownloadFile";
    /**
     * 缓存图片
     */
    public static String SDCARD_CACHE_IMAGE_DIR = SDCARD_APP_ROOT + File.separator + "CacheImage";
    /**
     * 图片裁剪
     */
    public static String SDCARD_CROP_IMAGE_DIR = SDCARD_APP_ROOT + File.separator + "CropImage";
    /**
     * 错误日志
     */
    public static String SDCARD_ERROR_DIR = SDCARD_APP_ROOT + File.separator + "errorlog";

    private static final String CACHE_DIR = "/data/data/";

    private static final String CACHE_DIR_SHARED = "/shared_prefs";

    private static final String CACHE_DIR_DB = "/databases";

    private static final String CACHE_DIR_CACHE = "/cache";


    /**
     * 判断sdcard是否存在，并返回sdcard路径。
     *
     * @return 返回sdcard路径
     */
    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);// 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();// 获取跟目录
        }
        if (sdDir == null) {
            return null;
        }
        return sdDir.toString();
    }

    /**
     * @return
     */
    public static String getExtSDCard() {
        try {
            Runtime runtime = Runtime.getRuntime();
            Process proc = runtime.exec("mount");
            InputStream is = proc.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            String line;
            String mount = new String();
            BufferedReader br = new BufferedReader(isr);
            while ((line = br.readLine()) != null) {
                if (line.contains("secure"))
                    continue;
                if (line.contains("asec"))
                    continue;

                if (line.contains("fat")) {
                    String columns[] = line.split(" ");
                    if (columns != null && columns.length > 1) {
                        mount = mount.concat(columns[1]);
                    }
                } /*
                 * else if (line.contains("fuse")) { String columns[] =
				 * line.split(" "); if (columns != null && columns.length > 1) {
				 * mount = mount.concat(columns[1] + "\n"); } }
				 */
            }
            return mount;
        } catch (FileNotFoundException e) {
            Logger.e(e.getMessage(), e);
        } catch (IOException e) {
            Logger.e(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 创建文件夹
     *
     * @return 返回文件夹路径
     */
    public static String createFolder(String dirFolder) {
        String extSdCard = getExtSDCard();
        if (extSdCard == null || "".equals(extSdCard)) {
            extSdCard = getSDPath();
        }
        File folder = new File(extSdCard + File.separator + dirFolder);
        if (folder.exists() == false) {
            folder.mkdirs(); // 创建文件夹完整路径
        }
        return folder.toString();
    }

    /**
     * 创建文件夹
     *
     * @return 返回文件夹路径
     */
    public static String createSDCardFolder(String dirFolder) {
        String extSdCard = getSDPath();
        if (TextUtils.isEmpty(extSdCard)) {
            extSdCard = getExtSDCard();
        }
        File folder = new File(extSdCard + File.separator + dirFolder);
        if (folder.exists() == false) {
            folder.mkdirs(); // 创建文件夹完整路径
        }
        return folder.toString();
    }

    /**
     * 创建文件夹
     *
     * @return 返回文件夹路径
     */
    public static String createDefaultFolder(String dirFolder) {
        File folder = new File(getSDPath() + File.separator + dirFolder);
        if (folder.exists() == false) {
            folder.mkdirs(); // 创建文件夹完整路径
        }
        return folder.toString();
    }

    /**
     * 创建文件
     *
     * @return 返回文件路径
     */
    public static String createFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {// 文件存在返回false
            try {
                file.createNewFile();// 创建文件
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file.toString();
    }

    /**
     * 判断指定是否文件存在
     *
     * @param filePath
     * @return
     */
    public static boolean isExistFile(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return false;
        }
        boolean flag = false;
        try {
            File file = new File(filePath);
            if (file.exists()) {
                flag = true; // 指定文件存在
            } else {
                flag = false;
            }
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }


    /**
     * 清除所有缓存文件
     *
     * @param filePath
     * @return
     */
    public static boolean deleteFolder(Context context, String filePath) {
        boolean flag = false;
        File file = new File(filePath);
        if (file.isDirectory()) {
            String[] children = file.list();
            for (int i = 0; i < children.length; i++) {
                File f = new File(file, children[i]);
                f.delete();
            }
            flag = file.delete(); // 创建文件夹完整路径
        } else {
            Toast.makeText(context, "已经完全清除缓存文件，请返回！", Toast.LENGTH_LONG).show();
        }
        return flag;
    }

    /**
     * 删除存在多级目录中的文件
     *
     * @param filepath
     * @throws IOException
     */
    public static boolean delFolders(String filepath) {
        boolean flag = false;
        try {
            File f = new File(filepath);// 定义文件路径
            if (f.exists() && f.isDirectory()) {// 判断是文件还是目录
                if (f.listFiles().length == 0) {// 若目录下没有文件则直接删除
                    f.delete();
                } else {// 若有则把文件放进数组，并判断是否有下级目录
                    File delFile[] = f.listFiles();
                    int i = f.listFiles().length;
                    for (int j = 0; j < i; j++) {
                        if (delFile[j].isDirectory()) {
                            delFolders(delFile[j].getAbsolutePath());// 递归调用del方法并取得子目录路径
                        }
                        flag = delFile[j].delete();// 删除文件
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return flag;
    }

    /**
     * 单个文件拷贝。
     *
     * @param srcFile   源文件
     * @param destFile  目标文件
     * @param overwrite 是否覆盖目的文件
     * @throws IOException
     */
    public static void copyFile(File srcFile, File destFile, boolean overwrite) {
        BufferedInputStream inputStream = null;
        BufferedOutputStream outputStream = null;
        byte[] block = new byte[1024];
        try {
            // 首先判断源文件是否存在
            if (!srcFile.exists()) {
                throw new FileNotFoundException("Cannot find the source file: " + srcFile.getAbsolutePath());
            }
            // 判断源文件是否可读
            if (!srcFile.canRead()) {
                throw new IOException("Cannot read the source file: " + srcFile.getAbsolutePath());
            }

            if (overwrite == false) {
                // 目标文件存在就不覆盖
                if (destFile.exists())
                    return;
            } else {
                // 如果要覆盖已经存在的目标文件，首先判断是否目标文件可写。
                if (destFile.exists()) {
                    if (!destFile.canWrite()) {
                        throw new IOException("Cannot write the destination file: " + destFile.getAbsolutePath());
                    }
                } else {
                    // 不存在就创建一个新的空文件。
                    if (!destFile.createNewFile()) {
                        throw new IOException("Cannot write the destination file: " + destFile.getAbsolutePath());
                    }
                }
            }

            inputStream = new BufferedInputStream(new FileInputStream(srcFile));
            outputStream = new BufferedOutputStream(new FileOutputStream(destFile));
            while (true) {
                int readLength = inputStream.read(block);
                if (readLength == -1)
                    break;// end of file
                outputStream.write(block, 0, readLength);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException ex) {
                    // just ignore
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException ex) {
                    // just ignore
                }
            }
        }
    }

    /**
     * 拷贝文件，从源文件夹拷贝文件到目的文件夹。 <br>
     * 参数源文件夹和目的文件夹，最后都不要带文件路径符号，例如：c:/aa正确，c:/aa/错误。
     *
     * @param srcDirName  源文件夹名称 ,例如：c:/test/aa 或者c://test//aa
     * @param destDirName 目的文件夹名称,例如：c:/test/aa 或者c://test//aa
     * @param overwrite   是否覆盖目的文件夹下面的文件。
     * @throws IOException
     */
    public static void copyFiles(String srcDirName, String destDirName, boolean overwrite) throws IOException {
        File srcDir = new File(srcDirName);// 声明源文件夹
        // 首先判断源文件夹是否存在
        if (!srcDir.exists()) {
            throw new FileNotFoundException("Cannot find the source directory: " + srcDir.getAbsolutePath());
        }

        File destDir = new File(destDirName);
        if (overwrite == false) {
            if (!destDir.exists()) {
                if (destDir.mkdirs() == false) {
                    throw new IOException("Cannot create the destination directories = " + destDir);
                }
            }
        } else {
            // 覆盖存在的目的文件夹
            if (!destDir.exists()) {
                // create a new directory
                if (destDir.mkdirs() == false) {
                    throw new IOException("Cannot create the destination directories = " + destDir);
                }
            }
        }

        // 循环查找源文件夹目录下面的文件（屏蔽子文件夹），然后将其拷贝到指定的目的文件夹下面。
        File[] srcFiles = srcDir.listFiles();
        if (srcFiles == null || srcFiles.length < 1) {
            return;// do nothing
        }

        // 开始复制文件
        int SRCLEN = srcFiles.length;

        for (int i = 0; i < SRCLEN; i++) {
            File destFile = new File(destDirName + File.separator + srcFiles[i].getName());
            // 注意构造文件对象时候，文件名字符串中不能包含文件路径分隔符";".
            if (srcFiles[i].isFile()) {
                copyFile(srcFiles[i], destFile, overwrite);
            } else {
                // 在这里进行递归调用，就可以实现子文件夹的拷贝
                copyFiles(srcFiles[i].getAbsolutePath(), destDirName + File.separator + srcFiles[i].getName(), overwrite);
            }
        }
    }


    /**
     * 拆开文件（String）并存入到List集合里
     *
     * @param files
     * @return
     */
    public static List<String> detachFilesStringToList(String files) {
        List<String> sList = new ArrayList<String>();
        if (files != null && !files.equals("")) {
            if (files.indexOf(";") != -1) {
                String[] filePaths = files.split(";");
                for (String s : filePaths) {
                    sList.add(s);
                }
            } else {
                sList.add(files);
            }
        }
        return sList;
    }

    /**
     * @param file
     * @return
     */
    public static boolean deleteFile(File file) {
        try {
            File[] fs = file.listFiles();
            if (fs != null) {
                for (File f : fs) {
                    if (f.isDirectory()) {
                        deleteFile(f);
                        f.delete();
                    } else {
                        f.delete();
                    }
                }
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * @param zipFile
     * @param toDir
     */
    public static void Unzip(String zipFile, String toDir) {
        int BUFFER = 4096; // 这里缓冲区我们使用4KB，
        String entryFileName; // 保存每个zip的条目名称
        try {
            BufferedOutputStream dest = null; // 缓冲输出流
            FileInputStream fis = new FileInputStream(zipFile);
            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
            ZipEntry entry; // 每个zip条目的实例
            while ((entry = zis.getNextEntry()) != null) {
                try {
                    int count;
                    byte data[] = new byte[BUFFER];
                    entryFileName = entry.getName();

                    File entryFile = new File(toDir, entryFileName);

                    FileOutputStream fos = new FileOutputStream(entryFile);
                    dest = new BufferedOutputStream(fos, BUFFER);
                    while ((count = zis.read(data, 0, BUFFER)) != -1) {
                        dest.write(data, 0, count);
                    }
                    dest.flush();
                    dest.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            zis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        File f = new File(zipFile);
//        f.delete();
    }

    /**
     * 打开文件
     *
     * @param file 文件路径
     * @param ctx  上下文
     */
    public static void openFile(String file, Context ctx) {
        Intent intent = IntentUtils.getIntent(file);
        ctx.startActivity(intent);
    }

    private static class IntentUtils {
        // 获取文件扩展名
        private static String getExName(String file) {
            // TODO Auto-generated method stub
            return file.substring(file.lastIndexOf(".") + 1, file.length())
                    .toLowerCase();
        }

        public static Intent getIntent(String filePath) {

            String end = getExName(filePath);
            // 根据不同文件类型，获得相应intent
            if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")
                    || end.equals("xmf") || end.equals("ogg")
                    || end.equals("wav")) {
                return getAudioFileIntent(filePath);
            } else if (end.equals("3gp") || end.equals("mp4")) {
                return getAudioFileIntent(filePath);
            } else if (end.equals("jpg") || end.equals("gif")
                    || end.equals("png") || end.equals("jpeg")
                    || end.equals("bmp")) {
                return getImageFileIntent(filePath);
            } else if (end.equals("apk")) {
                return getApkFileIntent(filePath);
            } else if (end.equals("ppt")) {
                return getPptFileIntent(filePath);
            } else if (end.equals("xls")) {
                return getExcelFileIntent(filePath);
            } else if (end.equals("doc")) {
                return getWordFileIntent(filePath);
            } else if (end.equals("pdf")) {
                return getPdfFileIntent(filePath);
            } else if (end.equals("chm")) {
                return getChmFileIntent(filePath);
            } else if (end.equals("txt")) {
                return getTextFileIntent(filePath, false);
            } else {
                return getAllIntent(filePath);
            }

        }

        /**
         * @param param
         * @return
         */
        public static Intent getAllIntent(String param) {

            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri = Uri.fromFile(new File(param));
            intent.setDataAndType(uri, "*/*");
            return intent;
        }

        /**
         * Android获取一个用于打开APK文件的intent
         *
         * @param param
         * @return
         */
        public static Intent getApkFileIntent(String param) {

            Intent intent = new Intent();
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);
            Uri uri = Uri.fromFile(new File(param));
            intent.setDataAndType(uri,
                    "application/vnd.android.package-archive");
            return intent;
        }

        /**
         * Android获取一个用于打开VIDEO文件的intent
         *
         * @param param
         * @return
         */
        public static Intent getVideoFileIntent(String param) {

            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("oneshot", 0);
            intent.putExtra("configchange", 0);
            Uri uri = Uri.fromFile(new File(param));
            intent.setDataAndType(uri, "video/*");
            return intent;
        }

        /**
         * Android获取一个用于打开AUDIO文件的intent
         *
         * @param param
         * @return
         */
        public static Intent getAudioFileIntent(String param) {

            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("oneshot", 0);
            intent.putExtra("configchange", 0);
            Uri uri = Uri.fromFile(new File(param));
            intent.setDataAndType(uri, "audio/*");
            return intent;
        }

        /**
         * Android获取一个用于打开Html文件的intent
         *
         * @param param
         * @return
         */
        public static Intent getHtmlFileIntent(String param) {

            Uri uri = Uri.parse(param).buildUpon()
                    .encodedAuthority("com.android.htmlfileprovider")
                    .scheme("content").encodedPath(param).build();
            Intent intent = new Intent("android.intent.action.VIEW");
            intent.setDataAndType(uri, "text/html");
            return intent;
        }

        /**
         * Android获取一个用于打开图片文件的intent
         *
         * @param param
         * @return
         */
        public static Intent getImageFileIntent(String param) {

            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(new File(param));
            intent.setDataAndType(uri, "image/*");
            return intent;
        }

        /**
         * Android获取一个用于打开PPT文件的intent
         *
         * @param param
         * @return
         */
        public static Intent getPptFileIntent(String param) {

            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(new File(param));
            intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
            return intent;
        }

        /**
         * Android获取一个用于打开Excel文件的intent
         *
         * @param param
         * @return
         */
        public static Intent getExcelFileIntent(String param) {

            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(new File(param));
            intent.setDataAndType(uri, "application/vnd.ms-excel");
            return intent;
        }

        /**
         * Android获取一个用于打开Word文件的intent
         *
         * @param param
         * @return
         */
        public static Intent getWordFileIntent(String param) {

            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(new File(param));
            intent.setDataAndType(uri, "application/msword");
            return intent;
        }

        /**
         * Android获取一个用于打开CHM文件的intent
         *
         * @param param
         * @return
         */
        public static Intent getChmFileIntent(String param) {

            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(new File(param));
            intent.setDataAndType(uri, "application/x-chm");
            return intent;
        }

        /**
         * Android获取一个用于打开文本文件的intent
         *
         * @param param
         * @param paramBoolean
         * @return
         */
        public static Intent getTextFileIntent(String param,
                                               boolean paramBoolean) {

            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (paramBoolean) {
                Uri uri1 = Uri.parse(param);
                intent.setDataAndType(uri1, "text/plain");
            } else {
                Uri uri2 = Uri.fromFile(new File(param));
                intent.setDataAndType(uri2, "text/plain");
            }
            return intent;
        }

        /**
         * Android获取一个用于打开PDF文件的intent
         *
         * @param param
         * @return
         */
        public static Intent getPdfFileIntent(String param) {

            Intent intent = new Intent("android.intent.action.VIEW");
            intent.addCategory("android.intent.category.DEFAULT");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.fromFile(new File(param));
            intent.setDataAndType(uri, "application/pdf");
            return intent;
        }
    }

    /**
     * 一行一行写入到文件中
     *
     * @param filePath
     * @param str
     */
    public static void writeLine(String filePath, String str) {
        FileWriter fw = null;
        File file = new File(filePath);
        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(filePath, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(str);
            bw.newLine();
            bw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 一行一行读取文件
     *
     * @param filePath
     * @return
     */
    public static List<String> readLine(String filePath) {
        File file = new File(filePath);
        BufferedReader reader = null;
        List<String> sList = new ArrayList<String>();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                sList.add(tempString);
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return sList;
    }


    /**
     * 清除缓存数据
     *
     * @param packageName
     */
    public static void clearCacheFiles(String packageName) {
        String cacheDir = CACHE_DIR + packageName;
        String sharedPath = cacheDir + CACHE_DIR_SHARED;
        String dbPath = cacheDir + CACHE_DIR_DB;
        String cachePath = cacheDir + CACHE_DIR_CACHE;
        FileUtil.delFolders(dbPath);
        FileUtil.delFolders(sharedPath);
        FileUtil.delFolders(cachePath);
    }

    /**
     * @param folderPath
     * @param fileName
     * @return
     */
    public static String getFilePath(String folderPath, String fileName) {
        if (TextUtils.isEmpty(fileName)) {
            return "";
        }
        String filePath = createSDCardFolder(folderPath) + File.separator + fileName;
        return filePath;
    }


    /**
     * @param folderName
     * @param fileName
     */
    public static void delFile(String folderName, String fileName) {
        File file = new File(createSDCardFolder(folderName) + File.separator + fileName);
        if (file.isFile()) {
            file.delete();
        }
        file.exists();
    }


    /**
     * @param stream
     */
    private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * loadFromAssets
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String loadFromAssets(Context context, String fileName) {
        BufferedReader reader = null;
        try {
            InputStream in = context.getResources().getAssets().open(fileName);
            reader = new BufferedReader(new InputStreamReader(in));

            char[] buf = new char[1024];
            int count = 0;
            StringBuffer sb = new StringBuffer(in.available());
            while ((count = reader.read(buf)) != -1) {
                String readData = String.valueOf(buf, 0, count);
                sb.append(readData);
            }

            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeStream(reader);
        }

        return "";
    }

    /**
     * 拷贝文件
     * 如果目标文件不存在将会自动创建
     *
     * @param srcFile  原文件
     * @param saveFile 目标文件
     * @return 是否拷贝成功
     */
    public static boolean copyFile(final File srcFile, final File saveFile) {
        File parentFile = saveFile.getParentFile();
        if (!parentFile.exists()) {
            if (!parentFile.mkdirs())
                return false;
        }

        BufferedInputStream inputStream = null;
        BufferedOutputStream outputStream = null;
        try {
            inputStream = new BufferedInputStream(new FileInputStream(srcFile));
            outputStream = new BufferedOutputStream(new FileOutputStream(saveFile));
            byte[] buffer = new byte[1024 * 4];
            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            IOUtil.close(inputStream, outputStream);
        }
        return true;
    }

    /**
     * 写文本文件 在Android系统中，文件保存在 /data/data/PACKAGE_NAME/files 目录下
     *
     * @param context
     * @param
     */
    public static void write(Context context, String fileName, String content) {
        if (content == null)
            content = "";

        try {
            FileOutputStream fos = context.openFileOutput(fileName,
                    Context.MODE_PRIVATE);
            fos.write(content.getBytes());

            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取文本文件
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String read(Context context, String fileName) {
        try {
            FileInputStream in = context.openFileInput(fileName);
            return readInStream(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @param inStream
     * @return
     */
    public static String readInStream(InputStream inStream) {
        try {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[512];
            int length = -1;
            while ((length = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, length);
            }

            outStream.close();
            inStream.close();
            return outStream.toString();
        } catch (IOException e) {
            Log.i("readInStream", e.getMessage());
        }
        return null;
    }

    /**
     * @param folderPath
     * @param fileName
     * @return
     */
    public static File createFile(String folderPath, String fileName) {
        File destDir = new File(folderPath);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        return new File(folderPath, fileName + fileName);
    }

    /**
     * 向手机写图片
     *
     * @param buffer
     * @param folder
     * @param fileName
     * @return
     */
    public static boolean writeFile(byte[] buffer, String folder,
                                    String fileName) {
        boolean writeSucc = false;

        boolean sdCardExist = Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED);

        String folderPath = "";
        if (sdCardExist) {
            folderPath = Environment.getExternalStorageDirectory()
                    + File.separator + folder + File.separator;
        } else {
            writeSucc = false;
        }

        File fileDir = new File(folderPath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }

        File file = new File(folderPath + fileName);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            out.write(buffer);
            writeSucc = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return writeSucc;
    }

    /**
     * 根据文件绝对路径获取文件名
     *
     * @param filePath
     * @return
     */
    public static String getFileName(String filePath) {
        if (TextUtils.isEmpty(filePath))
            return "";
        return filePath.substring(filePath.lastIndexOf(File.separator) + 1);
    }

    /**
     * 根据文件的绝对路径获取文件名但不包含扩展名
     *
     * @param filePath
     * @return
     */
    public static String getFileNameNoFormat(String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            return "";
        }
        int point = filePath.lastIndexOf('.');
        return filePath.substring(filePath.lastIndexOf(File.separator) + 1,
                point);
    }

    /**
     * 获取文件扩展名
     *
     * @param fileName
     * @return
     */
    public static String getFileFormat(String fileName) {
        if (TextUtils.isEmpty(fileName))
            return "";

        int point = fileName.lastIndexOf('.');
        return fileName.substring(point + 1);
    }

    /**
     * 获取文件大小
     *
     * @param filePath
     * @return
     */
    public static long getFileSize(String filePath) {
        long size = 0;

        File file = new File(filePath);
        if (file != null && file.exists()) {
            size = file.length();
        }
        return size;
    }

    /**
     * 获取文件大小
     *
     * @param size 字节
     * @return
     */
    public static String getFileSize(long size) {
        if (size <= 0)
            return "0";
        java.text.DecimalFormat df = new java.text.DecimalFormat("##.##");
        float temp = (float) size / 1024;
        if (temp >= 1024) {
            return df.format(temp / 1024) + "M";
        } else {
            return df.format(temp) + "K";
        }
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return B/KB/MB/GB
     */
    public static String formatFileSize(long fileS) {
        java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }

    /**
     * 获取目录文件大小
     *
     * @param dir
     * @return
     */
    public static long getDirSize(File dir) {
        if (dir == null) {
            return 0;
        }
        if (!dir.isDirectory()) {
            return 0;
        }
        long dirSize = 0;
        File[] files = dir.listFiles();
        if (files != null) {

            for (File file : files) {
                if (file.isFile()) {
                    dirSize += file.length();
                } else if (file.isDirectory()) {
                    dirSize += file.length();
                    dirSize += getDirSize(file); // 递归调用继续统计
                }
            }
        }
        return dirSize;
    }

    /**
     * 获取目录文件个数
     *
     * @param
     * @return
     */
    public long getFileList(File dir) {
        long count = 0;
        File[] files = dir.listFiles();
        count = files.length;
        for (File file : files) {
            if (file.isDirectory()) {
                count = count + getFileList(file);// 递归
                count--;
            }
        }
        return count;
    }

    /**
     * 检查文件是否存在
     *
     * @param name
     * @return
     */
    public static boolean checkFileExists(String name) {
        boolean status;
        if (!name.equals("")) {
            File path = Environment.getExternalStorageDirectory();
            File newPath = new File(path.toString() + name);
            status = newPath.exists();
        } else {
            status = false;
        }
        return status;
    }

    /**
     * 检查路径是否存在
     *
     * @param path
     * @return
     */
    public static boolean checkFilePathExists(String path) {
        return new File(path).exists();
    }

    /**
     * 计算SD卡的剩余空间
     *
     * @return 返回-1，说明没有安装sd卡
     */
    public static long getFreeDiskSpace() {
        String status = Environment.getExternalStorageState();
        long freeSpace = 0;
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            try {
                File path = Environment.getExternalStorageDirectory();
                StatFs stat = new StatFs(path.getPath());
                long blockSize = stat.getBlockSize();
                long availableBlocks = stat.getAvailableBlocks();
                freeSpace = availableBlocks * blockSize / 1024;
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return -1;
        }
        return (freeSpace);
    }

    /**
     * 新建目录
     *
     * @param directoryName
     * @return
     */
    public static boolean createDirectory(String directoryName) {
        boolean status;
        if (!directoryName.equals("")) {
            File path = Environment.getExternalStorageDirectory();
            File newPath = new File(path.toString() + directoryName);
            status = newPath.mkdir();
            status = true;
        } else
            status = false;
        return status;
    }

    /**
     * 检查是否安装SD卡
     *
     * @return
     */
    public static boolean checkSaveLocationExists() {
        String sDCardStatus = Environment.getExternalStorageState();
        boolean status;
        if (sDCardStatus.equals(Environment.MEDIA_MOUNTED)) {
            status = true;
        } else
            status = false;
        return status;
    }

    /**
     * 检查是否安装外置的SD卡
     *
     * @return
     */
    public static boolean checkExternalSDExists() {

        Map<String, String> evn = System.getenv();
        return evn.containsKey("SECONDARY_STORAGE");
    }

    /**
     * 删除目录(包括：目录里的所有文件)
     *
     * @param fileName
     * @return
     */
    public static boolean deleteDirectory(String fileName) {
        boolean status;
        SecurityManager checker = new SecurityManager();

        if (!fileName.equals("")) {

            File path = Environment.getExternalStorageDirectory();
            File newPath = new File(path.toString() + fileName);
            checker.checkDelete(newPath.toString());
            if (newPath.isDirectory()) {
                String[] listfile = newPath.list();
                try {
                    for (int i = 0; i < listfile.length; i++) {
                        File deletedFile = new File(newPath.toString() + "/"
                                + listfile[i].toString());
                        deletedFile.delete();
                    }
                    newPath.delete();
                    Log.i("deleteDirectory", fileName);
                    status = true;
                } catch (Exception e) {
                    e.printStackTrace();
                    status = false;
                }

            } else
                status = false;
        } else
            status = false;
        return status;
    }

    /**
     * 删除文件
     *
     * @param fileName
     * @return
     */
    public static boolean deleteFile(String fileName) {
        boolean status;
        SecurityManager checker = new SecurityManager();

        if (!fileName.equals("")) {

            File path = Environment.getExternalStorageDirectory();
            File newPath = new File(path.toString() + fileName);
            checker.checkDelete(newPath.toString());
            if (newPath.isFile()) {
                try {
                    Log.i("deleteFile", fileName);
                    newPath.delete();
                    status = true;
                } catch (SecurityException se) {
                    se.printStackTrace();
                    status = false;
                }
            } else
                status = false;
        } else
            status = false;
        return status;
    }

    /**
     * 清除指定缓存文件
     *
     * @param filePath
     * @return
     */
    public static boolean deleteFile2(String filePath) {
        boolean flag = false;
        try {
            File file = new File(filePath);
            if (file.exists()) {
                flag = file.delete(); // 删除指定文件
            }
        } catch (Exception e) {
            Logger.d("delete file failure..");
            flag = false;
        }
        return flag;
    }


    /**
     * 删除空目录
     * <p/>
     * 返回 0代表成功 ,1 代表没有删除权限, 2代表不是空目录,3 代表未知错误
     *
     * @return
     */
    public static int deleteBlankPath(String path) {
        File f = new File(path);
        if (!f.canWrite()) {
            return 1;
        }
        if (f.list() != null && f.list().length > 0) {
            return 2;
        }
        if (f.delete()) {
            return 0;
        }
        return 3;
    }

    /**
     * 重命名
     *
     * @param oldName
     * @param newName
     * @return
     */
    public static boolean reNamePath(String oldName, String newName) {
        File f = new File(oldName);
        return f.renameTo(new File(newName));
    }

    /**
     * 删除文件
     *
     * @param filePath
     */
    public static boolean deleteFileWithPath(String filePath) {
        SecurityManager checker = new SecurityManager();
        File f = new File(filePath);
        checker.checkDelete(filePath);
        if (f.isFile()) {
            Log.i("deleteFile", filePath);
            f.delete();
            return true;
        }
        return false;
    }

    /**
     * 清空一个文件夹
     *
     * @param
     */
    public static void clearFileWithPath(String filePath) {
        List<File> files = FileUtil.listPathFiles(filePath);
        if (files.isEmpty()) {
            return;
        }
        for (File f : files) {
            if (f.isDirectory()) {
                clearFileWithPath(f.getAbsolutePath());
            } else {
                f.delete();
            }
        }
    }


    /**
     * 获取SD卡的根目录
     *
     * @return
     */
    public static String getSDRoot() {

        return Environment.getExternalStorageDirectory().getAbsolutePath();
    }

    /**
     * 获取手机外置SD卡的根目录
     *
     * @return
     */
    public static String getExternalSDRoot() {

        Map<String, String> evn = System.getenv();

        return evn.get("SECONDARY_STORAGE");
    }

    /**
     * 列出root目录下所有子目录
     *
     * @param
     * @return 绝对路径
     */
    public static List<String> listPath(String root) {
        List<String> allDir = new ArrayList<String>();
        SecurityManager checker = new SecurityManager();
        File path = new File(root);
        checker.checkRead(root);
        // 过滤掉以.开始的文件夹
        if (path.isDirectory()) {
            for (File f : path.listFiles()) {
                if (f.isDirectory() && !f.getName().startsWith(".")) {
                    allDir.add(f.getAbsolutePath());
                }
            }
        }
        return allDir;
    }

    /**
     * 获取一个文件夹下的所有文件
     *
     * @param root
     * @return
     */
    public static List<File> listPathFiles(String root) {
        List<File> allDir = new ArrayList<File>();
        SecurityManager checker = new SecurityManager();
        File path = new File(root);
        checker.checkRead(root);
        File[] files = path.listFiles();
        for (File f : files) {
            if (f.isFile())
                allDir.add(f);
            else
                listPath(f.getAbsolutePath());
        }
        return allDir;
    }


    public enum PathStatus {
        SUCCESS, EXITS, ERROR
    }

    /**
     * 创建目录
     *
     * @param
     */
    public static PathStatus createPath(String newPath) {
        File path = new File(newPath);
        if (path.exists()) {
            return PathStatus.EXITS;
        }
        if (path.mkdir()) {
            return PathStatus.SUCCESS;
        } else {
            return PathStatus.ERROR;
        }
    }

    /**
     * 截取路径名
     *
     * @return
     */
    public static String getPathName(String absolutePath) {
        int start = absolutePath.lastIndexOf(File.separator) + 1;
        int end = absolutePath.length();
        return absolutePath.substring(start, end);
    }

    /**
     * 获取应用程序缓存文件夹下的指定目录
     *
     * @param context
     * @param dir
     * @return
     */
    public static String getAppCache(Context context, String dir) {
        String savePath = context.getCacheDir().getAbsolutePath() + "/" + dir + "/";
        File savedir = new File(savePath);
        if (!savedir.exists()) {
            savedir.mkdirs();
        }
        savedir = null;
        return savePath;
    }

    public static InputStream getStreamFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return null;
        }
        try {
            InputStream stream = new FileInputStream(file);
            return stream;
        } catch (FileNotFoundException e) {
            Logger.e(e.getMessage(), e);
        }
        return null;
    }

    public static BufferedInputStream getStreamFile(File file) {
        if (!file.exists())
            return null;
        try {
            BufferedInputStream stream = new BufferedInputStream(new FileInputStream(file));
            return stream;
        } catch (FileNotFoundException e) {
            Logger.e(e.getMessage(), e);
        }
        return null;
    }


}
